﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Windows.Data;
using common4gp;

namespace wpf4gp.Converters
{

    /// <summary>
    /// Converts a number to a <see cref="System.String"/> with 2 decimals
    /// </summary>
    public class DecimalStringConverter : IValueConverter
    {

        /// <summary>
        /// Converts a number to a <see cref="System.String"/> with 2 decimals
        /// </summary>
        /// <returns>The <see cref="System.String"/> that contains the number without decimals</returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Contract.Ensures(Contract.Result<object>().IsNotNull());
            string result = string.Empty;
            if (value.IsNotNull() &&
                value.IsNumber())
            {
                result = string.Format("{0:n2}", value);
            }
            return result;
        }

        /// <summary>
        /// Converts a <see cref="System.String"/> to a <see cref="System.Decimal"/>
        /// </summary>
        /// <returns><see cref="System.Decimal"/> rappresented by the <see cref="System.String"/></returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Contract.Ensures(Contract.Result<object>().IsNotNull());
            decimal result = 0;
            if (value.IsNotNull())
            {
                string strValue = value as string;
                decimal.TryParse(strValue, out result);
            }
            return result;
        }
    }
}
